<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/13
 * Time: 10:47
 */

namespace app\mobile\controller;


use app\admin\model\Users;
use app\common\traits\Wechat;
use think\Controller;
use think\Db;

class Login extends Controller
{
    use Wechat;
    /**
     * 登陆显示
     * @return mixed
     */
    public function login(){
        if (is_login()) $this->redirect('mobile/index/index');//在一次判断是否登陆
        $url = session('order_url');
        if (is_weixin()) $this->sendWechatCheck($url) ;//判断是否在微信的场景登陆 在 求请求微信用户信息
        $this->redirect('admin/login/login');
    }
    /**
     * 发起微信userinfo 请求
     * @param null $url 针对存在order_id 参数又未登陆的情况
     */
    protected function sendWechatCheck($url){
//        if($url)$this->wechatapp['config']->set('oauth.callback',$url);
        is_null($url)?:session('jump',$url);//请求页面
        self::getInstance()->oauth->redirect()->send(); //发起网页授权请求
    }

    /**
     *处理微信回调后处理登陆的逻辑
     */
    public function receive(){
        $oauth = self::getInstance()->oauth;//获取微信回掉回来的东西
        $user = $oauth->user()->toArray();
        foreach ($user['original'] as $key => $value) {
            $user[$key]=$value;
        }
        unset($user['original']);
        unset($user['token']);
        $data = Users::get(['openid'=>$user['id']]);
        if(!empty($data)){
            if($data['status']!=1)$this->loginfaild('当前用户已被禁用,请联系管理人员！');
            $users = new Users();
            if($users->wechatlogin($user)) {
                empty(session('jump'))?$this->redirect('index/index'):$this->redirect(session('jump'));
            }else{
                $this->loginfaild('登陆失败,请联系管理人员！');
            }
        }else{
            session('we_user',$user);
            $this->redirect('login/bind');
        }
    }

    /**
     * 微信绑定页面
     * @return mixed
     */
    public function bind()
    {
        $info = session('we_user');
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     * 绑定手机号码
     * @return mixed
     */
    public function validate()
    {
        $data = input('post.');
        $info = session('we_user');
        if(empty($data['phone']))$this->error ('号码不能为空！');
        $user = Db::name('users')->where(['phone'=>$data['phone'],'weixinstatus'=>2,'status'=>1])->find();
        if($user){
            $re = Db::name('users')->where(['id'=>$user['id']])->update(['openid'=>$data['openid'],'weixinstatus'=>1,'headimgurl'=>$info['headimgurl']]);
            if($re){
                return $this->fetch('success');
            }else{
                $this->error('绑定失败，请联系管理员！');
            }
        }else{
            $this->error('绑定失败，系统没有找到该号码或者该号码已经被绑定！');
        }
    }

    /**
     * 绑定失败后跳转
     * @param string $msg
     * @return mixed
     */
    public function loginfaild($msg='用户不存在或被禁用')
    {
        $this->assign('failmsg',$msg);
        return $this->fetch('loginfaild');
    }
}